package com.xishu.controller;

import com.xishu.annotation.valid.Admin;
import com.xishu.annotation.valid.MethodValidator;
import com.xishu.aop.Validator;
import com.xishu.config.Constant;
import com.xishu.entity.Company;
import com.xishu.entity.User;
import com.xishu.entity.feedback.Feedback;
import com.xishu.entity.shop.Shop;
import com.xishu.response.ResponseData;
import com.xishu.service.CommonService;
import com.xishu.service.CompanyService;
import com.xishu.service.ShopService;
import com.xishu.service.UserService;
import com.xishu.util.ServletUtil;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(description = "反馈")
public class FeedbackController implements Tools {
    private CommonService commonService = CommonService.getInstance();
    private static Logger logger = LoggerFactory.getLogger(FeedbackController.class);

    @ApiOperation(value = "创建反馈")
    @MethodValidator(mustLogin = false)
    @PostMapping(value = ("/user/feedback"), produces = ("application/json;charset=UTF-8"))
    public ResponseData create(@RequestBody Feedback feedback) throws Exception {
        Validator validator = new Validator();
        User user = ServletUtil.getUser();
        feedback.setStatus(Constant.FEED_BACK_STATUS_INIT);

        //如果不是平台管理员 ，需要把回复相关的数据清空
        if (!validator.isShopManager(user)) {
            feedback.setParentId(null);
        }

        //已经反馈过的订单，不再次创建反馈
        Feedback newFeedback = new Feedback();
        newFeedback.setOrderId(feedback.getOrderId());
        Feedback feedbackInDb = commonService.searchOne(newFeedback);
        if (isNotEmpty(feedbackInDb)){
            return commonService.createResponse(feedbackInDb);
        }

        if (getLong(feedback.getParentId()) != 0) {
            //加上shopId
            Feedback parentFeedBack = commonService.findEntity(feedback.getParentId(), Feedback.class);
            feedback.setShopId(parentFeedBack.getShopId());
        }

        if (isEmpty(feedback.getContent()) && isNotEmpty(feedback.getFeedBackContent())) {
            feedback.setContent(feedback.getFeedBackContent());
        } else if (isNotEmpty(feedback.getContent()) && isEmpty(feedback.getFeedBackContent())) {
            feedback.setFeedBackContent(feedback.getContent());
        }

        //加上用户名
        if (user != null) {
            feedback.setUserName(UserService.getInstance().getShowUserName(user));
        }

        //前台要是没有传公司ID，后台加上
        if (feedback.getCompanyId() == null) {
            Long shopId = feedback.getShopId();
            if (shopId != null) {
                Shop shop = ShopService.getInstance().findShopById(shopId);
                feedback.setCompanyId(shop.getCompanyId());
            }
        }


        return CommonService.getInstance().createObject(feedback);
    }

    @ApiOperation(value = "修改反馈")
    @PutMapping(value = ("/user/feedback/modify"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    public ResponseData modify(@RequestBody Feedback feedback) throws Exception {
        return CommonService.getInstance().updateObject(feedback);
    }

    @ApiOperation(value = "查询反馈")
    @PutMapping(value = ("/user/feedback"), produces = ("application/json;charset=UTF-8"))
    public ResponseData search(@RequestBody Feedback feedback) throws Exception {
        feedback.setSortField(new String[]{"createTime"});
        feedback.setSortType("DESC");
        return CommonService.getInstance().searchResponse(feedback, (f) -> {
            try {
                if (f.getShopId() != null) {
                    Long shopId = f.getShopId();
                    ShopService shopService = ShopService.getInstance();
                    Shop shop = shopService.findShopById(shopId);
                    f.setShopName_zh(shopService.getShopName(shop));
                    f.setShopName_en(shopService.getShopNameEn(shop));
                    CompanyService companyService = CompanyService.getInstance();
                    Company company = companyService.findCompanyById(shop.getCompanyId());
                    f.setCompanyName(company.getName());
                } else if (f.getCompanyId() != null) {
                    CompanyService companyService = CompanyService.getInstance();
                    Company company = companyService.findCompanyById(f.getCompanyId());
                    f.setCompanyName(company.getName());
                }
            } catch (Exception e) {
                logger.error("e", e);
            }
        });

    }

    @ApiOperation(value = "删除反馈")
    @DeleteMapping(value = ("/user/feedback"), produces = ("application/json;charset=UTF-8"))
    @Admin
    public ResponseData delete(@RequestBody Feedback feedback) throws Exception {
        return CommonService.getInstance().delete(feedback);
    }
}
